package com.visu.common.validation;

import org.apache.commons.collections4.CollectionUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.validation.groups.Default;

/**
 *Created by 程振奇 on 2017/11/29.
 */
public class ValidationUtils {

    private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    public static <T> ValidationResultBean validateEntity(T obj) {
        ValidationResultBean result = new ValidationResultBean();
        Map<String, String> errorMsg = null;
        if (obj == null) {
            result.setHasErrors(true);
            errorMsg = new HashMap<String, String>();
            errorMsg.put("Object", "对象非法!");
            result.setErrorMsg(errorMsg);
            return result;
        }

        Set<ConstraintViolation<T>> set = validator.validate(obj, Default.class);
        if (CollectionUtils.isNotEmpty(set)) {
            result.setHasErrors(true);
            errorMsg = new HashMap<String, String>();
            for (ConstraintViolation<T> cv : set) {
                errorMsg.put(cv.getPropertyPath().toString(), cv.getMessage());
            }
            result.setErrorMsg(errorMsg);
        }
        return result;
    }

    public static <T> ValidationResultBean validateProperty(T obj, String propertyName) {
        ValidationResultBean result = new ValidationResultBean();
        Set<ConstraintViolation<T>> set = validator.validateProperty(obj, propertyName, Default.class);
        if (CollectionUtils.isNotEmpty(set)) {
            result.setHasErrors(true);
            Map<String, String> errorMsg = new HashMap<String, String>();
            for (ConstraintViolation<T> cv : set) {
                errorMsg.put(propertyName, cv.getMessage());
            }
            result.setErrorMsg(errorMsg);
        }
        return result;
    }





}